package com.example.research.controller;

import com.example.research.dto.ApiResponse;
import com.example.research.entity.VerticalProject;
import com.example.research.service.AuthService;
import com.example.research.service.VerticalProjectService;
import com.example.research.utils.PermissionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 纵向课题控制器
 */
@RestController
@RequestMapping("/vertical-projects")
@Validated
public class VerticalProjectController {

    @Autowired
    private VerticalProjectService verticalProjectService;

    @Autowired
    private AuthService authService;

    @Autowired
    private PermissionUtils permissionUtils;

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId(String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new RuntimeException("未提供有效的认证信息");
        }
        String token = authHeader.substring(7);
        return authService.getUserIdFromToken(token);
    }

    /**
     * 查询所有纵向课题
     */
    @GetMapping
    public ApiResponse<List<VerticalProject>> getAllProjects() {
        try {
            List<VerticalProject> projects = verticalProjectService.findAll();
            return ApiResponse.success(projects);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据ID查询纵向课题
     */
    @GetMapping("/{id}")
    public ApiResponse<VerticalProject> getProjectById(@PathVariable Long id) {
        try {
            VerticalProject project = verticalProjectService.findById(id);
            if (project == null) {
                return ApiResponse.notFound("纵向课题不存在");
            }
            return ApiResponse.success(project);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 查询当前用户的纵向课题
     */
    @GetMapping("/my")
    public ApiResponse<List<VerticalProject>> getMyProjects(@RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            List<VerticalProject> projects = verticalProjectService.findByUserId(userId);
            return ApiResponse.success(projects);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据审核状态查询纵向课题
     */
    @GetMapping("/audit-status/{status}")
    public ApiResponse<List<VerticalProject>> getProjectsByAuditStatus(@PathVariable Integer status) {
        try {
            List<VerticalProject> projects = verticalProjectService.findByAuditStatus(status);
            return ApiResponse.success(projects);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据项目级别查询纵向课题
     */
    @GetMapping("/level/{level}")
    public ApiResponse<List<VerticalProject>> getProjectsByLevel(@PathVariable String level) {
        try {
            List<VerticalProject> projects = verticalProjectService.findByProjectLevel(level);
            return ApiResponse.success(projects);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据条件查询纵向课题
     */
    @GetMapping("/search")
    public ApiResponse<List<VerticalProject>> searchProjects(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String projectLevel,
            @RequestParam(required = false) Integer auditStatus,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        try {
            List<VerticalProject> projects = verticalProjectService.findByConditions(
                    userId, projectLevel, auditStatus, startDate, endDate);
            return ApiResponse.success(projects);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 创建纵向课题
     */
    @PostMapping
    public ApiResponse<VerticalProject> createProject(@Valid @RequestBody VerticalProject project,
                                                     @RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.substring(7);
            Long userId = permissionUtils.getCurrentUserId(token);

            project.setUserId(userId);
            project.setReportDate(LocalDateTime.now()); // 设置填报日期

            // 设置默认值
            if (project.getAuditStatus() == null) {
                project.setAuditStatus(0); // 待审核
            }

            VerticalProject createdProject = verticalProjectService.createProject(project);
            return ApiResponse.success("纵向课题创建成功", createdProject);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 更新纵向课题
     */
    @PutMapping("/{id}")
    public ApiResponse<VerticalProject> updateProject(@PathVariable Long id,
                                                     @Valid @RequestBody VerticalProject project,
                                                     @RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.substring(7);
            Long userId = permissionUtils.getCurrentUserId(token);

            // 检查项目是否存在
            VerticalProject existingProject = verticalProjectService.findById(id);
            if (existingProject == null) {
                return ApiResponse.notFound("纵向课题不存在");
            }

            // 检查权限：只能修改自己的项目
            if (!existingProject.getUserId().equals(userId)) {
                return ApiResponse.forbidden("无权限修改此项目");
            }

            // 检查是否可以修改（审核通过后不可修改）
            if (!permissionUtils.canModifyAchievement(existingProject.getAuditStatus())) {
                return ApiResponse.error("项目已审核通过，无法修改");
            }

            project.setId(id);
            project.setUserId(userId);
            VerticalProject updatedProject = verticalProjectService.updateProject(project);
            return ApiResponse.success("纵向课题更新成功", updatedProject);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 删除纵向课题
     */
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteProject(@PathVariable Long id,
                                           @RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.substring(7);
            Long userId = permissionUtils.getCurrentUserId(token);

            // 检查项目是否存在
            VerticalProject existingProject = verticalProjectService.findById(id);
            if (existingProject == null) {
                return ApiResponse.notFound("纵向课题不存在");
            }

            // 检查权限：只能删除自己的项目
            if (!existingProject.getUserId().equals(userId)) {
                return ApiResponse.forbidden("无权限删除此项目");
            }

            // 检查是否可以删除（审核通过后不可删除）
            if (!permissionUtils.canModifyAchievement(existingProject.getAuditStatus())) {
                return ApiResponse.error("项目已审核通过，无法删除");
            }

            verticalProjectService.deleteProject(id, userId);
            return ApiResponse.success("纵向课题删除成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 提交审核
     */
    @PostMapping("/{id}/submit")
    public ApiResponse<String> submitForAudit(@PathVariable Long id,
                                            @RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            verticalProjectService.submitForAudit(id, userId);
            return ApiResponse.success("纵向课题提交审核成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}
